# -*- coding: utf-8 -*-

from odoo import models, fields, api
import logging

_logger = logging.getLogger(__name__)


class wliotPpmSensor(models.Model):
    _name = 'wliot.ppm.sensor'
    _inherit = ['mail.thread']
    _rec_name = 'barcode'

    # name = fields.Char(string=u'名称')
    device = fields.Many2one('wliot.device', string=u'设备')
    ppm_type_id = fields.Many2one('wliot.ppm.type', string=u'传感器型号', required=True)
    barcode = fields.Char(string=u'追溯号', required=True)
    status = fields.Selection([
        ('installed', u'安装'),
        ('uninstalled', u'未安装')
    ], string=u'状态')
    deadline_date = fields.Date(string=u'寿命到期日', required=True)
    partner_id = fields.Many2one('res.partner', string=u'客户', required=True)
    calibration = fields.Float(string=u'校准值', required=True)

    @api.multi
    def send_message1(self, subject, subtype, partner_ids):
        try:
            self.ensure_one()
            p_ids = []
            for partner_id in partner_ids:
                p_ids.append((partner_id,))
            print p_ids
            new_msg = self.message_post(subject=subject,
                                        message_type='notification',
                                        subtype=subtype,
                                        partner_ids=p_ids)
        except Exception as ex:
            _logger.error('error ' + ex.message)

    @api.model
    def send_message(self, subject, subtype, partner_ids):
        '''发送通知'''
        p_ids = []
        # for partner_id in partner_ids:
        #     p_ids.append((partner_id,))
        # print p_ids
        self.message_subscribe(partner_ids=partner_ids)
        body = u"<p>%s</p ><a target='_blank' href='www.baidu.com'>111</ a>" % (subject)
        post_vars = {
            'body': body,
            'partner_ids': partner_ids,
        }
        self.message_post(message_type="notification", subtype=subtype, **post_vars)

    def send_msg_to_user(self, partner_ids, subject, url, url_name):
        '''发送通知'''
        rec = self.browse(1).sudo()
        rec.message_subscribe(partner_ids=partner_ids)
        body = u"<p>%s</p ><a target='_blank' href='%s'>%s</ a>" % (subject, url, url_name)
        post_vars = {
            'body': body,
            'partner_ids': partner_ids,
        }
        rec.message_post(type="notification", subtype="mt_comment", **post_vars)
